<?php

namespace App\Ant\Excel\Imports;

use App\Models\Company\Archive;
use App\Models\Label;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class ArchiveImport implements ToCollection, WithChunkReading
{

    protected $items;

    protected $relationModel;

    protected $label;

    public function __construct(Model $model)
    {
        $this->init();
        $this->relationModel = $model;
        $name = $this->relationModel->region->name.'装修公司';
        $this->label = Label::where('name', $name)->first();
        if ($this->label == null) {
            $this->label = new Label([
                'name' => $name,
                'is_state' => true
            ]);
            $this->label->save();
        }
    }

    private function init()
    {
        $this->items = new Collection();
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $collection->each(function ($item) {
            $data = [
                'name'           => $item[0],
                'region_id'      => $this->relationModel->region_id,
                'type'           => $item[5],
                'business_scope' => $item[10],
                'location'       => $item[8],
                'credit_code'    => $item[3],
                'legal_person'   => $item[4],
                'established_at' => $item[6],
                'capital'        => $item[7],
                'email'          => $item[9],
                'tel'            => $item[12],
                'more_tel'       => $item[13],
                'website'        => $item[11],
                'task_id'        => $this->relationModel->id,
                'is_state'       => false,
                'is_top'         => $this->relationModel->is_top,
                'label_id'       => $this->label->id
            ];
            $this->items->push($data);
        });
        $this->relationModel->increment('sum_count', $this->items->count());
        if ($this->items->isNotEmpty()) {
            Archive::insert($this->items->toArray());
        }
        $this->init();
    }

    public function chunkSize(): int
    {
        return 1000;
    }

}